﻿using Microsoft.AspNetCore.Http;
using Syspetro.Core.SysInterface;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

namespace Syspetro.Core.HttpService
{
    public class AuthHeaderHandler : DelegatingHandler, ITransientService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

       
        public AuthHeaderHandler(IHttpContextAccessor httpContextAccessor )
        {
            _httpContextAccessor = httpContextAccessor;
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {// See if the request has an authorize header
            var auth = request.Headers.Authorization;
            if (auth != null)
            { var totalToken = _httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString();
                if (totalToken.Trim().Length>= auth.Scheme.Length)
                {
                    string token = totalToken[7..];

                    request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
                }
               
            }
            var response= await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

            return response;


        }
    }
}
